package com.LeeCode;

import java.util.Arrays;

/**
 * 拆炸弹
 */

public class Code1652 {
    public static void main(String[] args) {
        int[] code = {2, 4, 9, 3};
        int k = -2;
        System.out.println(Arrays.toString(new Code1652().decrypt(code, k)));
    }

    public int[] decrypt(int[] code, int k) {
        int[] ans = new int[code.length];
        if (k == 0) return ans;
        int curSum = 0, start;
        int window = Math.abs(k);

        for (start = 0; start < window; start++) {
            curSum += code[start];
        }

        if (k > 0) {
            ans[ans.length - 1] = curSum;
        } else {
            ans[window] = curSum;
        }

        for (start = 1; start < ans.length; start++) {
            int end = (start + window - 1) % ans.length;
            curSum += code[end] - code[start - 1];
            if (k > 0) {
                ans[start - 1] = curSum;
            } else {
                ans[(end + 1) % ans.length] = curSum;
            }
        }
        return ans;
    }

    public int[] decrypt1(int[] code, int k) {
        int n = code.length;
        int[] ans = new int[n];
        int r = k > 0 ? k + 1 : n; // 第一个窗口的右开端点
        k = Math.abs(k);
        int s = 0;
        for (int i = r - k; i < r; i++) {
            s += code[i]; // 计算 ans[0]
        }
        for (int i = 0; i < n; i++) {
            ans[i] = s;
            s += code[r % n] - code[(r - k) % n];
            r++;
        }
        return ans;
    }

}
